package com.shaonaiyi.hadoop.filetype.avro;

import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumWriter;

import java.io.File;
import java.io.IOException;

/**
 * @Author shaonaiyi@163.com
 * @Date 2019/12/17 16:17
 * @Description 编码实现写Avro文件
 */
public class AvroFileWriter {

    public static void main(String[] args) throws IOException {
        GenericRecord record1 = new GenericData.Record(Person.SCHEMA$);
        record1.put("name", "shaonaiyi");
        record1.put("age", 18);
        record1.put("favorite_number", 7);
        record1.put("favorite_color", "red");

        GenericRecord record2 = new GenericData.Record(Person.SCHEMA$);
        record2.put("name", "shaonaier");
        record2.put("age", 17);
        record2.put("favorite_number", 1);
        record2.put("favorite_color", "yellow");

        File file = new File("person.avro");
        DatumWriter<GenericRecord> writer = new GenericDatumWriter<>(Person.SCHEMA$);
        DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(writer);
        dataFileWriter.create(Person.SCHEMA$, file);
        dataFileWriter.append(record1);
        dataFileWriter.append(record2);
        dataFileWriter.close();

    }

}
